package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import model.Emocao;
import model.Questionario;

public class QuestionarioDAO {
	
	private Connection conexao;
	private Statement st;
	private ResultSet rs;
	Adaptador adaptador = new Adaptador();
	
	public void inserir(Questionario questionario) throws SQLException{
		conexao = adaptador.abrirConexao();
		ArrayList<Integer> emocoes = questionario.getEmocoes();
		ArrayList<Integer> respondentes = questionario.getRespondentes();
		String sql = "INSERT INTO questionario(cod_emocao, cod_respondente) VALUES (?, ?);";
		PreparedStatement ps = conexao.prepareStatement(sql);
		try{
			st = conexao.createStatement();
			for(int i = 0; i < respondentes.size(); i++){
				for(int j=0; j < emocoes.size(); j++){
					ps.setInt(2, respondentes.get(i));
					ps.setInt(1, emocoes.get(j));
					ps.execute();
				}
			}
		}
		catch(SQLException sqle){
			sqle.getMessage();
		}finally{
			conexao.close();
			st.close();
			ps.close();
		}
	}

	public Questionario getQuestionarioRespondente(int codigo) throws SQLException{
		Questionario questionario = new Questionario();
		ArrayList<Emocao> emocoes = new ArrayList<Emocao>();
		conexao = adaptador.abrirConexao();
		String sql = "SELECT q.*, e.* FROM Questionario q, Emocao e WHERE q.cod_respondente = ? and e.codigo = q.cod_emocao";
		PreparedStatement ps = conexao.prepareStatement(sql);
		try{
			st = conexao.createStatement();
			ps.setInt(1, codigo);
			rs = ps.executeQuery();
			while(rs.next()){
				String nomeDaEmocao = rs.getString("nome_emocao");
				int cod = rs.getInt("cod_emocao");
				Emocao emocao = new Emocao(nomeDaEmocao);
				emocao.setCodigo(cod);
				emocoes.add(emocao);
			}
			questionario.setEmocoesObj(emocoes);
		}catch(SQLException sqle){
			sqle.getMessage();
		}finally{
			conexao.close();
		}
		return questionario;
	}
}
